package com.tan.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ServiceProxyFactory {
    public static <T> T getService(T target){
        //jdk动态代理
        return (T)Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),new MyInvocationHandler(target));
    }
    //代理具体的业务
    public static class MyInvocationHandler implements InvocationHandler{
        private Object target;
        public MyInvocationHandler(Object target){
            this.target=target;
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println(method.getName()+"开始中=======");
            //执行原来的代码
            Object result = method.invoke(target, args);
            System.out.println(method.getName()+"执行完毕=======");
            return result;
        }
    }

    public static void main(String[] args) {
        //UserService userService=new UserServiceImpl();
        UserService userService=ServiceProxyFactory.getService(new UserServiceImpl());
        userService.add();
        userService.del();
    }
}
